package com.evan.common.connection;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import cn.skinapp.R;

import com.evan.common.utils.CommonUtility;

public class ConnectionCommon {

	private final int TIMEOUTTIME = 60000;

	// public String REQUESTPATH = "http://121.199.41.91:8081/kawamama/";
	public String REQUESTPATH,
			REQUESTPATH_PHP = "http://www.dzzyl.cn/admin/interface/",
			REQUEST_PIC_PATH;
	public final String NOCONNECTIONEXCEPTION = "<html";
	public final String JSONNULL = "[]";
	public final String CHARSET_PREFIX = "\ufeff";
	public String REQEUST_SUFFIX = ".do";

	private static ConnectionCommon connect = null;

	private String[] getSuffix = { ".txt", ".xml" };

	public static ConnectionCommon getInstance() {
		if (connect == null)
			connect = new ConnectionCommon();
		return connect;
	}

	private ConnectionCommon() {
	}

	public void setRequestPath(String requestPath) {
		this.REQUESTPATH = requestPath;
		if (CommonUtility.isNull(REQUEST_PIC_PATH)) {
			REQUEST_PIC_PATH = this.REQUESTPATH;
		}
	}

	public void setRequestPicPath(String requestPicPath) {
		this.REQUEST_PIC_PATH = requestPicPath;
	}

	public void setRequestSuffix(String suffix) {
		this.REQEUST_SUFFIX = suffix;
	}

	public synchronized String sendRequestFromHttpClient(Context context,
			String path, Map<String, Object> params, Handler handler) {
		// CommonUtility.tag(path);
		if (checkNetworkIsValid(context, handler)) {
			MultipartEntity entitydata = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			String a = "";
			if (params != null && !params.isEmpty()) {
				try {
					for (Map.Entry<String, Object> entry : params.entrySet()) {
						if (entry.getValue() instanceof File) {
							if (entry.getKey().contains("@@")) {
								entitydata.addPart(
										entry.getKey().substring(
												0,
												entry.getKey()
														.lastIndexOf("@@")),
										new FileBody((File) entry.getValue()));
							} else {
								entitydata.addPart(entry.getKey(),
										new FileBody((File) entry.getValue()));
							}
						} else {
							if (entry.getKey().contains("@@")) {
								entitydata.addPart(
										entry.getKey().substring(
												0,
												entry.getKey()
														.lastIndexOf("@@")),
										new StringBody(String.valueOf(entry
												.getValue()), Charset
												.forName("UTF-8")));
							} else {
								entitydata.addPart(
										entry.getKey(),
										new StringBody(String.valueOf(entry
												.getValue()), Charset
												.forName("UTF-8")));
							}
						}
						if ("token".equals(entry.getKey())
								&& !CommonUtility.isNull(entry.getValue())) {
							a += entry.getKey()
									+ "="
									+ URLEncoder.encode(entry.getValue()
											.toString(), "UTF-8") + "&";
						} else {
							a += entry.getKey() + "=" + entry.getValue() + "&";
						}
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				boolean isGet = false;
				for (String suffix : getSuffix) {
					if (path.contains(suffix)) {
						isGet = true;
						break;
					}
				}
				HttpPost post = null;
				HttpGet get = null;
				if (isGet) {
					get = new HttpGet(REQUESTPATH + path);
				} else {
					if (path.endsWith(".php")) {
						System.out.println(REQUESTPATH_PHP + path + "?" + a);
						post = new HttpPost(REQUESTPATH_PHP + path);
					} else {
						if (path.startsWith("http")) {
							System.out.println(path + "?" + a);
							post = new HttpPost(path);
						} else {
							System.out.println(REQUESTPATH + path + "?" + a);
							post = new HttpPost(REQUESTPATH + path);
						}
					}
				}
				
				
				Log.i("testlogin", "path:" + REQUESTPATH_PHP  + path);
				
				// HttpPost post = new HttpPost(REQUESTPATH + path);
				// + REQEUST_SUFFIX); // form

				DefaultHttpClient client = new DefaultHttpClient(); // 浏览器
				client.getParams().setParameter(
						CoreConnectionPNames.SO_TIMEOUT, TIMEOUTTIME);
				client.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUTTIME);
				HttpResponse response = null;
				if (!CommonUtility.isNull(post)) {
					post.setEntity(entitydata);
					response = client.execute(post);// 执行请求
				} else if (!CommonUtility.isNull(get)) {
					response = client.execute(get);
				}
				HttpEntity entity = response.getEntity();
				InputStream is = null;
				if (entity != null) {
					is = entity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is));
					StringBuffer buffer = new StringBuffer();
					String line;
					while ((line = reader.readLine()) != null) {
						buffer.append(line);
					}
					reader.close();
					is.close();
					if (buffer.indexOf(NOCONNECTIONEXCEPTION) != -1) {
						handler.sendEmptyMessage(R.string.server_exception);
						return null;
					}
					System.out.println(buffer + "======");
					post = null;
					get = null;
					reader = null;
					is = null;
					context = null;
					return removeFirstPrefix(buffer.toString());
				}
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				handler.sendEmptyMessage(R.string.client_exception);
			} catch (ConnectTimeoutException e) {
				e.printStackTrace();
				handler.sendEmptyMessage(R.string.connect_timeout);
			} catch (SocketTimeoutException e) {
				e.printStackTrace();
				handler.sendEmptyMessage(R.string.connect_timeout);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				handler.sendEmptyMessage(R.string.server_exception);
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendEmptyMessage(R.string.server_exception);
			} finally {
				handler = null;
				params = null;
				entitydata = null;
			}
			return null;
		} else {
			return null;
		}
	}

	public boolean checkNetworkIsValid(Context context, Handler handler) {
		if (checkNetwork(context))
			return true;
		else {
			if (handler != null)
				handler.sendEmptyMessage(R.string.network_invalid);
		}
		return false;
	}

	public boolean checkNetwork(Context context) {
		try {
			ConnectivityManager manager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkinfo = manager.getActiveNetworkInfo();
			if (networkinfo == null || !networkinfo.isAvailable()) {
				// 当前网络不可用
				return false;
			} else {
				// 当前网络可用
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private String removeFirstPrefix(String json) {
		if (!CommonUtility.isNull(json)) {
			if (json.startsWith(CHARSET_PREFIX)) {
				// json = json.replaceAll(CHARSET_PREFIX, "");
				json = json.substring(1);
			}
		}
		return json;
	}
}
